import Entity from './entity'

export default class StepDetailParent extends Entity {
    constructor(db, collectionName, foreginFieldName) {
        super(db, collectionName)

        this.foreginFieldName = foreginFieldName
    }

    async getDetailsById(id) {
        const list = await this.find({ [this.foreginFieldName]: id })
        return list
    }

    genToAddItem(item) {
        let clonedItem = JSON.parse(JSON.stringify(item))
        delete clonedItem.data.readOnly

        return {
            [this.foreginFieldName]: item[this.foreginFieldName],
            code: item.code,
            data: clonedItem.data
        }
    }

    genToUpdateItem(item) {
        let clonedItem = JSON.parse(JSON.stringify(item))
        delete clonedItem.data.readOnly

        return {
            code: item.code,
            data: clonedItem.data
        }
    }

    // 先删除所有明细，再重新新增
    async cleanAndSaveList(foreginFieldValue, list) {
        await this.delete({ [this.foreginFieldName]: foreginFieldValue })
        await this.insertMany(list.map(this.genToAddItem.bind(this)))
    }

    async statDetailCount() {
        const detailCountMap = await this.groupBy({}, `$${this.foreginFieldName}`)
        return detailCountMap
    }
}